package com.qf.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author 常肖飞先生
 * @version V1.0
 * @Project day41_1
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/11 11:08
 */
@WebServlet(name = "getCookieServlet",urlPatterns = "/getcookie")
public class getCookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取服务器之前创建的cookie。
        Cookie[] cookies = request.getCookies();
        //如果能获得cookie的数据，代表你之前来过。
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName());
            System.out.println(cookie.getValue());

            String name = cookie.getName();
            if(name.equals("uname")){
                response.getWriter().println(cookie.getValue());
            }
        }

        //增加cookie
        createCookie(request,response,"pwd","123",3000);
        //删除cookie uname
        createCookie(request,response,"uname","123",0);
        //修改cookie uname
        createCookie(request,response,"uname","tom",2000);

        //实现cookie保存中文。
        Cookie cookie = new Cookie(URLEncoder.encode("名字","utf-8"), URLEncoder.encode("张三","utf-8"));

        //获取中文
        URLDecoder.decode(cookie.getName(),"utf-8");//名字
        URLDecoder.decode(cookie.getValue(),"utf-8");//张三


    }

    private void createCookie(HttpServletRequest request,HttpServletResponse response,String key,String value,int lifeTime)throws IOException{
        //服务器端生成cookie  步骤
        //创建cookie
        Cookie cookie = new Cookie(key, value);
        //设置有效期
        // -1: 代表内存级别（浏览器窗口关闭，数据删除）
        // 0 : 删除当前数据。设置数据立即失效，删除指定的key的cookie。
        // >0: 设置浏览器端 cookie的保存的时长，单位是秒
        cookie.setMaxAge(lifeTime);
        //设置cookie的保存路径. 获取当前项目的上下文路径。/day41
        cookie.setPath(request.getContextPath());
        //设置 http协议只读
        cookie.setHttpOnly(true);
        //返回前端
        response.addCookie(cookie);

        response.getWriter().println("hello");
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
